package com.aida.evil.eda.Update;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;

import com.aida.evil.aida.R;
import com.aida.evil.eda.Data.NetworkData;
import com.aida.evil.eda.Window.CustomDialog;
import com.aida.evil.eda.Window.PopupWindows;

import java.io.File;

/****************************************************
 * com.aida.evil.eda.update.UpdateDownload
 * 作者：白雨濃  evil
 * 时间：16-3-10 16:47
 * 邮箱：evilbai@foxmail.com
 * 页面用途：用于升级操作，包含升级下载，弹出窗口
 ****************************************************/
public class UpdateDownload extends AppCompatActivity
{
    private static final String UPDATEURL = "http://" + NetworkData.ServiceIP + "/Update?";
    private static final String FILEPATH = "/storage/emulated/0/Eda";
    private static final String APPNAME = "Eda.apk";

    protected CompleteReceiver completeReceiver;/*广播接受者,用于传递到Welcome.class*/

    private CustomDialog.Builder builder;/*弹出中部窗口*/
    private PopupWindows popupWindows;/*弹出底部窗口*/
    private boolean complete = false;/*记录下载是否完成,默认为false*/


    /**
     * 在下载前判断网络状态
     *
     * @param NetType 传进来网络状态
     */
    protected void downloadDecideNet(String NetType)
    {
        if (NetType.equals("WIFI"))
        {
            download();/*下载*/
            dialog();/*弹出窗口*/
        }
        else
        {
            popupWindows = new PopupWindows(this, findViewById(R.id.welcome_layout)
                    , new String[]{"您正在使用4G/3G/2G\n是否继续更新？"}
                    , new String[]{"确认", "取消"})
            {
                @Override
                public void listView_1_OnClick(AdapterView<?> parent, View view, int position, long id)
                {

                }

                @Override
                public void listView_1_LongOnClick(AdapterView<?> parent, View view, int position, long id)
                {

                }

                @Override
                public void listView_2_OnClick(AdapterView<?> parent, View view, int position, long id)
                {
                    switch (position)
                    {
                        case 0:
                        {
                            download();/*下载*/
                            popupWindows.dismiss();
                            dialog();/*弹出窗口*/
                        }
                        break;
                        case 1:
                        {
                            finish();
                        }
                        break;
                    }
                }

                @Override
                public void listView_2_LongOnClick(AdapterView<?> parent, View view, int position, long id)
                {

                }
            };
            popupWindows.setTouchDismiss(false);
        }
    }

    /**
     * 弹出中部窗口
     */
    private void dialog()
    {
        builder = new CustomDialog.Builder(this);
        builder.setTitle("正在更新");
        builder.setContentView(View.inflate(this, R.layout.dialog_update_progress, null));
        builder.setCanceledOnTouchOutside(false);
        builder.setBackPressed(false);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                dialogDismiss();
            }
        });
        builder.show();
    }

    /**
     * 如果为下载完成,设置不能点击去确定,如果下载完成,可以点击确定
     */
    private void dialogDismiss()
    {
        if (complete)
        {
            builder.dismiss();
        }
    }

    /**
     * 下载
     */
    private void download()
    {
        String serviceString = Context.DOWNLOAD_SERVICE;

        DownloadManager downloadManager;
        downloadManager = (DownloadManager) getSystemService(serviceString);


        Uri uri = Uri.parse(UPDATEURL);

        DownloadManager.Request request = new DownloadManager.Request(uri);
        //指定大文件只能在wifi下进行
        //request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        //检测文件夹是否存在
        newdir(FILEPATH);
        //检测文件是否存在，如果存在，删除
        boolean b = deletefile();
        //表示在EdaUpdate文件夹，Eda.apk文件
        request.setDestinationInExternalPublicDir("Eda", APPNAME);
        //表示允许MediaScanner扫描到这个文件，默认不允许。
        request.allowScanningByMediaScanner();
        //设置下载中通知栏提示的标题
        request.setTitle("易答更新");
        //设置下载中通知栏提示的介绍
        request.setDescription("更新正在进行");
        /*表示下载进行中和下载完成的通知栏是否显示。
        默认只显示下载中通知。VISIBILITY_VISIBLE_NOTIFY_COMPLETED表示下载完成后显示通知栏提示。
        VISIBILITY_HIDDEN表示不显示任何通知栏提示
        ，这个需要在AndroidMainfest中添加权限
        android.permission.DOWNLOAD_WITHOUT_NOTIFICATION.*/
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

        //reference变量是系统为当前的下载请求分配的一个唯一的ID，
        //我们可以通过这个ID重新获得这个下载任务，进行一些自己想要进行的操作或者查询
        long reference = downloadManager.enqueue(request);
    }


    /**
     * 检测下载完成，接收广播执行的内部类
     */
    public class CompleteReceiver extends BroadcastReceiver
    {

        @Override
        public void onReceive(Context context, Intent intent)
        {
            // get complete download id
            long completeDownloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            // to do here
            openFiles(new File(FILEPATH + "/" + APPNAME));
            complete = true;/*设置下载完成记录为true*/
            builder.setCanceledOnTouchOutside(true);/*设置可以触摸外部消失*/
            builder.setBackPressed(true);/*下载完成,允许关闭窗口*/
        }
    }

    /**
     * 检测文件夹是否存在
     *
     * @param dir 文件夹名称
     *
     * @return 返回是否新建成功
     */
    private boolean newdir(String dir)
    {
        File folder = new File(dir);
        return (folder.exists() && folder.isDirectory()) || folder.mkdirs();
    }

    /**
     * 检测文件是否存在，如果存在，删除
     *
     * @return 返回是否删除成功
     */
    private boolean deletefile()
    {
        File file = new File(FILEPATH + "/" + APPNAME);
        if (file.exists())
        {
            return file.delete();
        }
        return false;
    }

    /**
     * 打开文件
     *
     * @param file
     */
    private void openFiles(File file)
    {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        //"application/vnd.android.package-archive"是apk的type
        intent.setDataAndType(Uri.fromFile(file),
                "application/vnd.android.package-archive");
        startActivity(intent);
    }
}
